<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['repaymentPlanId', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="还款方案名称">
          <a-input
            v-decorator="['repaymentPlanName', { rules: [{ required: true, message: '还款方案名称不能为空!' }] }]"
          />
        </a-form-item>
        <a-form-item label="开始时间">
          <a-date-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-decorator="['expiryStartTime', { rules: [{ required: true, message: '开始时间不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item label="截止时间">
          <a-date-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-decorator="['expiryEndTime', { rules: [{ required: true, message: '截止时间不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            placeholder="请选择状态"
            v-decorator="['status', { rules: [{ required: true, message: '请选择状态,状态不能为空！' }] }]"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="2">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 表单字段
const fields = ['repaymentPlanId', 'repaymentPlanName', 'expiryStartTime', 'expiryEndTime', 'status']

export default {
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this)
    }
  },
  methods: {
    /**
     * 提交表单
     */
    _submit: function () {
      this.$emit('ok')
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted () {}
}
</script>
